if (!isServer) exitWith {};

[] spawn {
    private _distThreshold = 1000;
    private _hiddenPos = [0, 0, 10];

    while {true} do {
        if (count allPlayers > 0) then {
            {
                if (!isPlayer _x && {alive _x} && {vehicle _x == _x}) then {
                    private _unit = _x;
                    private _isCached = _unit getVariable ["st_isCached", false];
                    private _checkPos = if (_isCached) then { _unit getVariable ["st_cachePos", getPosASL _unit] } else { getPosASL _unit }; 
                    private _nearestPlayer = [allPlayers, _checkPos] call BIS_fnc_nearestPosition;
                    private _dist = _checkPos distance _nearestPlayer;

                    if (_dist > _distThreshold && !_isCached) then {
                        _unit setVariable ["st_cachePos", getPosASL _unit];
                        _unit setVariable ["st_isCached", true];
                        _unit allowDamage false;
                        _unit enableSimulationGlobal false;
                        _unit hideObjectGlobal true;
                        _unit setPos _hiddenPos;
                    };

                    if (_dist <= _distThreshold && _isCached) then {
                        _unit setPosASL (_unit getVariable "st_cachePos");
                        _unit hideObjectGlobal false;
                        _unit enableSimulationGlobal true;
                        _unit allowDamage true;
                        _unit setVariable ["st_isCached", false];
                    };
                };
            } forEach allUnits;
        };
        sleep 5;
    };
};